//
//  LWRefreshControl.swift
//  Weibo
//
//  Created by kobe on 2016/12/28.
//  Copyright © 2016年 kobe. All rights reserved.
//

import UIKit

/// 刷新状态切换的临界点
fileprivate let LWRefreshOffset:CGFloat = 126

/// 刷新状态
///
/// - Normal:      普通状态
/// - Pulling:     超过临界点 如果放手开始刷新
/// - WillRefresh: 用户超过临界点 并且放手
enum LWRefreshState {
    case Normal
    case Pulling
    case WillRefresh
}

//刷新控件
class LWRefreshControl: UIControl {
    
    // MARK: - 属性
    
    /// 滚动视图的父视图 下拉刷新控件应该适用于 UITableView / UICollectionView
    fileprivate weak var scrollView: UIScrollView?
    
    fileprivate lazy var refreshView:LWRefreshView = LWRefreshView.refreshView()
    
    //MARK: - 构造函数
    init() {
        super.init(frame: CGRect())
        
        
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
        setupUI()
        
    }
    
    /*
        newSuperview : addSubviwe 方法会调用
        - 当添加父视图的时候 newSuperview 是父视图
        - 当父视图被移除 newSuperview 是nil
     
     */
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
//        print(newSuperview)
        
        //判断父视图的类型
        guard let sv = newSuperview as? UIScrollView else {
            return
        }
        
        //记录父视图
        scrollView = sv
        
        // KVO 监听父视图的contentOffset
        scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [], context: nil)
        
        
        
        
    }
    
    override func removeFromSuperview() {
        
        
        superview?.removeObserver(self, forKeyPath: "contentOffset")
        
        
        super.removeFromSuperview()
        
    }
    
    // 所有KVO方法会同一调用此方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
//        print(scrollView?.contentOffset)
        
        guard let sv = scrollView else {
            return
        }
        
        //初始高度就应该是0
        let height = -(sv.contentInset.top + sv.contentOffset.y)
        
        
        if height < 0 {
            return
        }
        
        //根据高度设置刷新控件的frame
        self.frame = CGRect(x: 0, y: -height, width: sv.bounds.width, height: height)
        
        // 传递父视图高度
        refreshView.parentViewHeight = height
        
        // 判断临界点 只需要判断一次
        if sv.isDragging {
            if height > LWRefreshOffset && refreshView.refreshState == .Normal {
                print("放手刷新")
                refreshView.refreshState = .Pulling
            } else if height <= LWRefreshOffset && refreshView.refreshState == .Pulling {
                print("再使劲")
                refreshView.refreshState = .Normal
                
            }
        } else {
            //放手 - 判断是否超过临界点
            if refreshView.refreshState == .Pulling {
                print("开始刷新")
                
                beginRefreshing()
                
                // 发送刷新数据的时间
                sendActions(for: .valueChanged)
                
            }
        }
        
        
    }
    
    func beginRefreshing() {
        print("开始刷新")
        
        // 判断父视图
        guard let sv = scrollView else {
            return
        }
        
        // 判断是否正在刷新 如果正在刷新 直接返回
        if refreshView.refreshState == .WillRefresh {
            return
        }
        
        // 设置刷新视图的状态
        refreshView.refreshState = .WillRefresh
        
        // 调整表格的间距
        var inset = sv.contentInset
        inset.top += LWRefreshOffset
        sv.contentInset = inset
        
        // 设置刷新视图的父视图高度
        refreshView.parentViewHeight = LWRefreshOffset
        
        
        
    }
    
    func endRefreshing() {
        print("结束刷新")
        
        guard let sv = scrollView else {
            return
        }
        
        // 判断是否正在刷新
        if refreshView.refreshState != .WillRefresh {
            return
        }
        
        // 恢复刷新视图的状态
        refreshView.refreshState = .Normal
        
        // 恢复表格视图的contentInset
        var inset = sv.contentInset
        inset.top -= LWRefreshOffset
        
        sv.contentInset = inset
        
    }
    
    
    
    
}

extension LWRefreshControl {
    fileprivate func setupUI() {
        backgroundColor = superview?.backgroundColor
        
        // 设置超出边界不显示
//        clipsToBounds = true
        
        addSubview(refreshView)
        
        // 自动布局
        refreshView.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1.0, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.width))
        addConstraint(NSLayoutConstraint(item: refreshView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: refreshView.bounds.height))
        
    }
}






